package com.yiwei.zxp.activity;

import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.yiwei.zxp.BussinessMainActivity;
import com.yiwei.zxp.R;
import com.yiwei.zxp.adapter.RankAdapter;
import com.yiwei.zxp.api.Api;
import com.yiwei.zxp.api.bean.ShopAddBean;
import com.yiwei.zxp.api.bean.ShopMallListBean;
import com.yiwei.zxp.api.model.CateGoryModel;
import com.yiwei.zxp.api.model.ShopIndexModel;
import com.yiwei.zxp.base.BaseActivity;
import com.yiwei.zxp.event.HomePagerEvent;
import com.yiwei.zxp.event.ShopCartEvent;
import com.yiwei.zxp.util.Network;
import com.yiwei.zxp.util.RxLifeUtil;
import com.yiwei.zxp.util.ToastUtil;
import com.yiwei.zxp.util.Util;
import com.yiwei.zxp.view.OnLoadeMoreListener;
import com.yiwei.zxp.view.V19FrameLayout;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by xsooy-pc on 17-12-8.
 */

public class RankActivity extends BaseActivity {


    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.txt_title)
    TextView txtTitle;
    @BindView(R.id.layout_title)
    V19FrameLayout layoutTitle;
    @BindView(R.id.tablayout)
    TabLayout tablayout;
    @BindView(R.id.list)
    RecyclerView list;
    @BindView(R.id.layout_empty)
    LinearLayout layoutEmpty;
    @BindView(R.id.refresh)
    SwipeRefreshLayout refresh;
    @BindView(R.id.txt_num)
    TextView txtNum;
    @BindView(R.id.btn_cart)
    FrameLayout btnCart;
    private Unbinder unbiner;
    private RankAdapter adapter;
    private int currentPage;
    private String cate_id;
    private OnLoadeMoreListener onLoadeMoreListener = new OnLoadeMoreListener() {
        @Override
        public void onLoadMore(int page) {
            getShopMallList(page);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ranking);
        initBar();
        unbiner = ButterKnife.bind(this);
        init();
    }

    private void init() {
        refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                if (TextUtils.isEmpty(cate_id)) {
                    getCateGory();
                } else {
                    onLoadeMoreListener.setPage(1);
                    getShopMallList(1);
                }
            }
        });
        txtTitle.setText("排行榜");
        adapter = new RankAdapter(this);
        adapter.setOnChooseListener(new RankAdapter.OnChooseListener() {
            @Override
            public void onClick(String shop_id, String goods_id, String goods_no) {
                getAddCart(shop_id, goods_id, goods_no);
            }
        });
        list.addOnScrollListener(onLoadeMoreListener);
        list.setAdapter(adapter);
        getCateGory();
        getShopCartCount();
    }


    public void getAddCart(String shop_id, String goods_id, String goods_no) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        refresh.setRefreshing(true);
        ShopAddBean bean = new ShopAddBean();
        bean.goods_id = goods_id;
        bean.shop_id = shop_id;
        bean.goods_no = goods_no;
        Api.api_service.getShopAdd(bean).compose(RxLifeUtil.loginCheckOn(this)).
                doFinally(() -> {
                    try {
                        refresh.setRefreshing(false);
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    EventBus.getDefault().post(new ShopCartEvent());
                    ToastUtil.makeCartTips("加入购物车成功");
                    getShopCartCount();
                });
    }

    public void getShopCartCount() {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        Api.api_service.getShopCartCount().compose(RxLifeUtil.NocheckOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    if (result.code.equals("00")) {
                        if (result.datas.num == 0) {
                            txtNum.setVisibility(View.GONE);
                        } else {
                            txtNum.setVisibility(View.VISIBLE);
                            txtNum.setText(result.datas.num + "");
                        }
                    }
                });
    }

    public void getCateGory() {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }
        refresh.setRefreshing(true);

        Api.api_service.getShopIndex().compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        refresh.setRefreshing(false);
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    setCateData(result.datas.cats);
                });
    }

    private void setCateData(List<ShopIndexModel.DatasBean.CatsBean> datas) {
        for (int i = 0; i < datas.size(); i++) {
            tablayout.addTab(tablayout.newTab().setText(datas.get(i).catname));
            if (i == 0) {
                cate_id = datas.get(i).id;
            }
        }
        tablayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {

                cate_id = datas.get(tab.getPosition()).id;


                onLoadeMoreListener.setPage(1);
                getShopMallList(1);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        getShopMallList(1);
    }

    public void getShopMallList(int page) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        refresh.setRefreshing(true);
        ShopMallListBean bean = new ShopMallListBean();
        bean.page = page;
        bean.order_by = "2";
        bean.cate_id = cate_id;
        Api.api_service.getShopMallList(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        refresh.setRefreshing(false);
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    adapter.add(result.datas, page == 1);
//                    setShopMallList(page, result.datas);
                    if (adapter.getItemCount() == 0) {
                        layoutEmpty.setVisibility(View.VISIBLE);
                    } else {
                        layoutEmpty.setVisibility(View.GONE);
                    }
                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbiner.unbind();
        unbiner = null;
    }


    @OnClick({R.id.btn_back, R.id.btn_cart})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_back:
                finish();
                break;
            case R.id.btn_cart:
                EventBus.getDefault().post(new HomePagerEvent(2));
                Util.startActivity(this, BussinessMainActivity.class);
                finish();
                break;
        }
    }
}
